package ext.tianma.cascade.datautility;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

import org.apache.log4j.Logger;

import wt.fc.Persistable;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.WTReference;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.session.SessionHelper;
import wt.util.WTException;

import com.ptc.core.components.descriptor.DataUtility;
import com.ptc.core.components.descriptor.ModelContext;
import com.ptc.core.components.factory.dataUtilities.DefaultDataUtility;
import com.ptc.core.components.rendering.guicomponents.AttributeInputCompositeComponent;
import com.ptc.core.components.rendering.guicomponents.ComboBox;
import com.ptc.core.components.rendering.guicomponents.GUIComponentArray;
import com.ptc.core.components.util.AttributeHelper;
import com.ptc.core.lwc.server.PersistableAdapter;
import com.ptc.core.meta.type.common.impl.DefaultTypeInstance;
import com.ptc.core.ui.resources.ComponentMode;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.tianma.cascade.util.CascadeHelper;

public class PartSequenceNumberDataUtility extends DefaultDataUtility {

	public Object getDataValue(String s, Object obj, ModelContext modelcontext) throws WTException {
		System.out.println("=============================start=============================");
		
		Object obj1 = null;

		String columnname = "";

		Object obj2 = modelcontext.getRawValue();
		String s2 = AttributeHelper.getStringValue(obj2, null, modelcontext.getATS(false));

		DataUtility datautility = getTypeBasedDataUtility(modelcontext);
		if (datautility != null) {

			obj1 = datautility.getDataValue(s, obj, modelcontext);

			if (obj1 instanceof AttributeInputCompositeComponent) {

				AttributeInputCompositeComponent component = (AttributeInputCompositeComponent) obj1;
				columnname = component.getColumnName();

			}
		}

		Persistable persistable = null;
//		NmCommandBean cb = modelcontext.getNmCommandBean();
//		 obj = cb.getPrimaryOid().getRefObject();
//		 System.out.println("obj====>>>"+obj);
//	       if (obj instanceof WTPart) {
//	       	System.out.println("=====wtpart====");
//	       }
		if(obj instanceof DefaultTypeInstance) {
			
			String id = ((DefaultTypeInstance)obj).getPersistenceIdentifier();
			System.out.println("id====>>"+id);
			if(id != null) {
				WTReference wtreference = new ReferenceFactory().getReference(id);
				persistable = wtreference.getObject();
				System.out.println("persistable==>>"+persistable);
			}
		}
	
		ComponentMode mode = modelcontext.getDescriptorMode();
		System.out.println("mode=====>>>"+mode);
		if (mode == ComponentMode.CREATE || mode == ComponentMode.EDIT) {
			String name = columnname + "_col_" + columnname;

			ComboBox combobox = getComponent(s2, (WTObject) persistable);
			combobox.setSelected(s2);
//			combobox.setRequired(true); 
			combobox.setId(s);
			combobox.setName(name);

			combobox.addJsAction("onChange", "changeSequenceNumber(this)");
			combobox.setTooltip("");
			GUIComponentArray guicomponentarray = new GUIComponentArray();
			guicomponentarray.addGUIComponent(combobox);
			obj1 = guicomponentarray;

		}

		return obj1;
	}

	protected ComboBox getComponent(String value, WTObject obj) throws WTException {
		ArrayList<String> list = null;
		System.out.println("obj====>>>"+obj);
		if(obj != null) {
			String groupnumber = getValue(obj, CascadeHelper.CASCADETYPE_GROUPSNUMBER).toString();
			System.out.println("groupnumber===>>"+groupnumber);
			Collection<String> coll = CascadeHelper.getCascadeData(CascadeHelper.CASCADETYPE_SEQUENCENUMBER, groupnumber);
			System.out.println("coll====>>"+coll);
			if(coll != null) {
				list = new ArrayList<String>();
				for (String str : coll) {
					System.out.println("str===>>"+str);
					list.add(str);
				}
			}
		}
		ComboBox combobox = new ComboBox(list, list, null);
		return combobox;
	}
	
	/**
	 * 
	 * @param p
	 * @param key
	 * @return
	 * @throws WTException
	 */
	public static Object getValue(Persistable p, String key) throws WTException {
		Locale loc = null;
		try {
			loc = SessionHelper.getLocale();
		} catch (WTException e) {
			e.printStackTrace();
			return null;

		}
		return getValue(p, loc, key);
	}
	
	/**
	 * 
	 * @param p
	 * @param key
	 * @return
	 * @throws WTException
	 */
	public static Object getValue(Persistable p, Locale loc, String key)
			throws WTException {
		PersistableAdapter lwcObject = new PersistableAdapter(p, null, loc,
				null);
		lwcObject.load(key);
		return lwcObject.get(key);

	}

	private DataUtility getTypeBasedDataUtility(ModelContext modelcontext) throws WTException {
		Class class1 = modelcontext.getRawType();
		if (class1 == null) {
			log.debug("getTypeBasedDataUtility(): no data utility could be determined because property value was null");
			return null;
		}
		Class class2 = getDataUtilityClassForAttributeType(class1);
		if (class2 != null) {
			try {
				return (DataUtility) class2.newInstance();
			} catch (Exception exception) {
				throw new WTException(exception);
			}
		} else {
			log.debug((new StringBuilder())
					.append("getTypeBasedDataUtility(): no default data utility was found for property of type ")
					.append(class1.toString()).toString());
			return null;
		}
	}

	private Class getDataUtilityClassForAttributeType(Class class1) {
		Class class2 = null;
		if (java.lang.Number.class.isAssignableFrom(class1)
				|| com.ptc.core.meta.common.FloatingPoint.class.isAssignableFrom(class1)
				|| wt.units.FloatingPointWithUnits.class.isAssignableFrom(class1) || isPrimitiveNumericType(class1))
			class2 = com.ptc.core.components.factory.dataUtilities.NumericDataUtility.class;
		else if (java.lang.String.class.isAssignableFrom(class1))
			class2 = com.ptc.core.components.factory.dataUtilities.StringDataUtility.class;
		else if (java.lang.Boolean.class.isAssignableFrom(class1) || Boolean.TYPE.isAssignableFrom(class1))
			class2 = com.ptc.core.components.factory.dataUtilities.BooleanDataUtility.class;
		else if (java.sql.Timestamp.class.isAssignableFrom(class1))
			class2 = com.ptc.core.components.factory.dataUtilities.DateDataUtility.class;
		else if (com.ptc.core.meta.common.Hyperlink.class.isAssignableFrom(class1))
			class2 = com.ptc.core.components.factory.dataUtilities.UrlDataUtility.class;
		else if (com.ptc.core.richtext.RichText.class.isAssignableFrom(class1))
			class2 = com.ptc.core.components.factory.dataUtilities.RichTextDataUtility.class;
		return class2;
	}

	private boolean isPrimitiveNumericType(Class class1) {
		return Byte.TYPE.isAssignableFrom(class1) || Short.TYPE.isAssignableFrom(class1)
				|| Integer.TYPE.isAssignableFrom(class1) || Long.TYPE.isAssignableFrom(class1)
				|| Float.TYPE.isAssignableFrom(class1) || Double.TYPE.isAssignableFrom(class1);
	}

	private static final Logger log;

	static {
		try {
			log = LogR.getLogger(PartSequenceNumberDataUtility.class.getName());
		} catch (Exception exception) {
			throw new ExceptionInInitializerError(exception);
		}
	}

}
